package org.igeek.atomqq.task;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.igeek.atomqq.AtomQQApplication;
import org.igeek.atomqq.domain.Friend;
import org.igeek.atomqq.net.HttpConnection;
import org.igeek.atomqq.net.Response;
import org.igeek.atomqq.net.HttpConnection.Request_TYPE;
import org.igeek.atomqq.service.MessageReceiver;
import org.igeek.atomqq.util.URLManager;
import org.igeek.atomqq.vo.MsgChat;
import org.igeek.atomqq.vo.MsgFriend;
import org.igeek.atomqq.vo.MsgFriendListChange;
import org.igeek.atomqq.vo.MsgFriendStatus;
import org.igeek.atomqq.vo.MsgGroup;
import org.igeek.atomqq.vo.MsgSysGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 消息轮询器，用以获取各种即时消息，上到系统消息，下到聊天消息
 * @author 作者 E-mail:hangxin1940@gmail.com
 * @version 创建时间：2011-9-3 上午01:45:15
 */
public class MessagePoll extends SingleAsyncTask<Void, Void, Void> {
	
	private static final String LOG_NAME="atomqq";
	
	
	/** 广播好友消息 */
	public static final String BROADCAST_MSG_FRIEND="org.igeek.message.friend";
	/** 广播群消息 */
	public static final String BROADCAST_MSG_GROUP="org.igeek.message.group";
	/** 广播好友状态变更 */
	public static final String BROADCAST_MSG_FRIEND_STATUS="org.igeek.message.friendstatus";
	/** 广播好友列表变更 */
	public static final String BROADCAST_MSG_FRIEND_LSTCHG="org.igeek.message.friendlstchg";
	/** 广播好系统群消息 */
	public static final String BROADCAST_MSG_SYS_GROUP="org.igeek.message.sysgroup";
	
	private boolean beRun;
	
	private BlockingQueue<String> threadQueue;
	
	private Context context;
	
	private Thread messageThread;
	
	private Intent intentFriend;
	private Intent intentGroup;
	private Intent intentFriendStatus;
	private Intent intentSysGroup;
	private Intent intentFriendListChg;
	
	
	public MessagePoll(Context context) throws Exception {
		this.context=context;
		messageThread=new Thread(messageRunner);
		
		intentFriend=new Intent(BROADCAST_MSG_FRIEND);
		intentGroup=new Intent(BROADCAST_MSG_GROUP);
		intentFriendStatus=new Intent(BROADCAST_MSG_FRIEND_STATUS);
		intentSysGroup=new Intent(BROADCAST_MSG_SYS_GROUP);
		intentFriendListChg=new Intent(BROADCAST_MSG_FRIEND_LSTCHG);
	}
	
	public void start()	{
		beRun=true;
		messageThread.start();
	}
	
	public void stop(){
		beRun=false;
		messageThread.stop();
	}
	
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			try{
				
				
				String msgs=msg.getData().getString("message");
				
				
				JSONObject re=new JSONObject(msgs);
				int retcode=re.getInt("retcode");
				//如果是消息,组装成非标准bean
				if(retcode==0){
					
					
					
					JSONArray res=new JSONArray();
					res=re.getJSONArray("result");
					
					ArrayList<MsgGroup> gms=new ArrayList<MsgGroup>();
					ArrayList<MsgFriend> fms=new ArrayList<MsgFriend>();
					
					for(int i=0;i<res.length();i++){
						JSONObject message=res.getJSONObject(i);
						String poll_type=message.getString("poll_type");
						
						//如果是群系统消息
						if("sys_g_msg".equals(poll_type)){
							MsgSysGroup gsmessage=createMsgSysGroup(message);
							
							
							intentSysGroup.putExtra(MessageReceiver.BROADCAST_TYPE, MessageReceiver.BROADCAST_TYPE_SYS_GROUP);
							intentSysGroup.putExtra(BROADCAST_MSG_FRIEND, gsmessage);
							context.sendOrderedBroadcast(intentFriend,MessageReceiver.PERMISSION);
							
							
						}
						//如果是群消息
						else if("group_message".equals(poll_type)){
							
							MsgGroup gmessage=createMsgGroup(message); 
							
							intentGroup.putExtra(MessageReceiver.BROADCAST_TYPE, MessageReceiver.BROADCAST_TYPE_GROUP);
							intentGroup.putExtra(BROADCAST_MSG_GROUP, gmessage);
							context.sendOrderedBroadcast(intentGroup,MessageReceiver.PERMISSION);
							
							
							
						}
						//如果是好友信息
						else if("message".equals(poll_type)){
							
							MsgFriend msgFriend=createMsgFriend(message);

							intentFriend.putExtra(MessageReceiver.BROADCAST_TYPE, MessageReceiver.BROADCAST_TYPE_FRIEND);
							intentFriend.putExtra(BROADCAST_MSG_FRIEND, msgFriend);
							context.sendOrderedBroadcast(intentFriend,MessageReceiver.PERMISSION);
							
						}
						//如果是好友状态信息
						else if("buddies_status_change".equals(poll_type)){
							
							MsgFriendStatus fsmessage=createMsgFriendStatus(message);
							
							intentFriendStatus.putExtra(MessageReceiver.BROADCAST_TYPE, MessageReceiver.BROADCAST_TYPE_FRIEND_STATUS);
							intentFriendStatus.putExtra(BROADCAST_MSG_FRIEND_STATUS, fsmessage);
							context.sendOrderedBroadcast(intentFriendStatus,MessageReceiver.PERMISSION);
							
							
							
						}
						//好友列表变更
						else if("buddylist_change".equals(poll_type)){
							MsgFriendListChange mflc=createMsgFriendListChange(message);

							intentFriendListChg.putExtra(MessageReceiver.BROADCAST_TYPE, MessageReceiver.BROADCAST_TYPE_FRIEND_LISTCHG);
							intentFriendListChg.putExtra(BROADCAST_MSG_FRIEND_LSTCHG, mflc);
							context.sendOrderedBroadcast(intentFriendListChg,MessageReceiver.PERMISSION);
							
							
							
						}
						
						
					}	
					
					
					
					
				}
			
			}catch (Exception e) {
				e.printStackTrace();
			}
			
			
		};
	};
	
	private Runnable messageRunner=new Runnable() {
		
		@Override
		public void run() {
			while(beRun){
			
				String clientid=HttpConnection.getCookieManager().getCookieValue("clientid");
				String psession=HttpConnection.getCookieManager().getCookieValue("psessionid");
				
				try {
					JSONObject r=new JSONObject();
						r.put("clientid", clientid);
					r.put("psessionid",psession );
					r.put("key", 0);
					
					JSONArray ids=new JSONArray();
					r.put("ids", ids);
					
					
					StringBuffer urls=new StringBuffer(URLManager.MESSAGE_POLL);
					urls.append("?r=");
					urls.append(URLEncoder.encode(r.toString(),"UTF-8"));
					urls.append("&clientid=");
					urls.append(clientid);
					urls.append("&psessionid=");
					urls.append(psession);
					
					try {
						URL url=new URL(urls.toString());
						HttpConnection conn=new HttpConnection(url, Request_TYPE.POST);
						conn.setReferer(URLManager.REFER_d_web2_qq_com_proxy);
						conn.connect();
						Response res=conn.getResponse();
						String json=res.getText();
						
						Message msg=new Message();
						Bundle bundle=new Bundle();
						bundle.putSerializable("message", json);
						msg.setData(bundle);
						handler.sendMessage(msg);
						
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	};
	
	
	/**这里用来处理服务器发送来的数据*/
	private Runnable handlerRunner=new Runnable() {
		
		@Override
		public void run() {
			
			
			while(beRun){
				try {
					
					
					
				} catch (Exception e) {
				}
			}
		}
		

	};


	@Override
	protected Void doInBackground(Void... params) {
		
		return null;
	}
	
	/**
	 * 组装好友列表改变消息
	 * @param json
	 * @return
	 * @throws JSONException
	 */
	private MsgFriendListChange createMsgFriendListChange(JSONObject json) throws JSONException{
		MsgFriendListChange msg=new MsgFriendListChange();
		JSONObject value=json.getJSONObject("value");
		
		List<Friend> addf=new ArrayList<Friend>();
		JSONArray addj=value.getJSONArray("added_friends");
		for(int i=1;i<addj.length();i++){
			JSONObject j=addj.getJSONObject(i);
			long uin=j.getLong("uin");
			int cid=j.getInt("groupid");
			
			Friend f=new Friend(uin);
			f.setCategory(cid);
			
			addf.add(f);
		}
		
		List<Friend> removef=new ArrayList<Friend>();
		JSONArray remj=value.getJSONArray("removed_friends");
		for(int i=1;i<remj.length();i++){
			JSONObject j=remj.getJSONObject(i);
			long uin=j.getLong("uin");
			
			Friend f=new Friend(uin);
			
			removef.add(f);
		}
		
		msg.setAddFriends(addf);
		msg.setRemovedFriends(removef);
		return msg;
	}
	
	/**
	 * 组装群系统消息
	 * @param jsonsg
	 * @return
	 * @throws JSONException
	 */
	private MsgSysGroup createMsgSysGroup(JSONObject jsonsg) throws JSONException{
		MsgSysGroup msg=new MsgSysGroup();
		
		JSONObject value=jsonsg.getJSONObject("value");
		msg.setMsg_id(value.getInt("msg_id"));
		msg.setFrom_uin(value.getLong("from_uin"));
		msg.setTo_uin(value.getLong("to_uin"));
		msg.setMsg_id2(value.getInt("msg_id2"));
		msg.setMsg_type(value.getInt("msg_type"));
		msg.setReply_ip(value.getLong("reply_ip"));
		msg.setGcode(value.getLong("gcode"));
		msg.setType(value.getString("type"));
		msg.setT_gcode(value.getLong("t_gcode"));
		msg.setOp_type(value.getInt("op_type"));
		msg.setNew_member(value.getLong("new_member"));
		msg.setT_new_member(value.getLong("t_new_member"));
		msg.setAdmin_uin(value.getLong("admin_uin"));
		msg.setAdmin_nick(value.getString("admin_nick"));
		
		return msg;
		
	}
	
	/**
	 * 组装好友状态变更消息
	 * @param jsonFStatus
	 * @return
	 * @throws JSONException 
	 */
	private MsgFriendStatus createMsgFriendStatus(JSONObject jsonFStatus) throws JSONException{
		MsgFriendStatus msgFs=new MsgFriendStatus();
		

		JSONObject value=jsonFStatus.getJSONObject("value");
		msgFs.setClient_type(value.getInt("client_type"));
		msgFs.setUin(value.getLong("uin"));
		msgFs.setStatus(value.getString("status"));
		
		return msgFs;
	}
	
	/**
	 * 组装群消息
	 * @param jsonGroup
	 * @return
	 * @throws JSONException 
	 */
	private MsgGroup createMsgGroup(JSONObject jsonGroup) throws JSONException{
		MsgGroup msgGroup=new MsgGroup();
		
		JSONObject value=jsonGroup.getJSONObject("value");
		msgGroup.setMsg_id(value.getInt("msg_id"));
		msgGroup.setFrom_uin(value.getLong("from_uin"));
		msgGroup.setTo_uin(value.getLong("to_uin"));
		msgGroup.setMsg_id2(value.getInt("msg_id2"));
		msgGroup.setMsg_type(value.getInt("msg_type"));
		msgGroup.setReply_ip(value.getLong("reply_ip"));
		msgGroup.setGroup_code(value.getLong("group_code"));
		msgGroup.setSend_uin(value.getLong("send_uin"));
		msgGroup.setSeq(value.getInt("seq"));
		msgGroup.setTime(value.getLong("time")*1000);
		msgGroup.setInfo_seq(value.getLong("info_seq"));
		
		
		JSONArray content=value.getJSONArray("content");
		msgGroup.setMessageContents(getMessageChat(content));
		
		return msgGroup;
	}
	
	
	/**
	 * 组装好友消息
	 * @param jsonFriend
	 * @throws JSONException 
	 */
	private MsgFriend createMsgFriend(JSONObject jsonFriend) throws JSONException{
		MsgFriend fmessage=new MsgFriend();
		
		JSONObject value=jsonFriend.getJSONObject("value");
		fmessage.setMsg_id(value.getInt("msg_id"));
		fmessage.setFrom_uin(value.getLong("from_uin"));
		fmessage.setMsg_id2(value.getInt("msg_id2"));
		fmessage.setMsg_type(value.getInt("msg_type"));
		fmessage.setReply_ip(value.getLong("reply_ip"));
		fmessage.setTime(value.getLong("time")*1000);
		
		JSONArray content=value.getJSONArray("content");
		fmessage.setMessageContents(getMessageChat(content));
		
		return fmessage;
	}
	
	
	
	
	/**获取消息内容
	 * @throws JSONException */
	private List<MsgChat> getMessageChat(JSONArray content) throws JSONException {
		List<MsgChat> chats=new ArrayList<MsgChat>();
		
		
		for(int i=1;i<content.length();i++){
			MsgChat cmessage=new MsgChat();
			
			
			String msg=content.getString(i);
			
			//如果当前信息是个图片
			if(msg.startsWith("[")){
				
				JSONArray m=new JSONArray(msg);
				String type=m.getString(0);
				
				//如果是默认表情
				if("face".equals(type)){
					cmessage.setContentType(MsgChat.ContentType.FACE);
					cmessage.setContent(String.format("%03d", m.getInt(1)));
				}
				//如果是个自定义表情或图片
				else if("cface".equals(type)){
					cmessage.setContentType(MsgChat.ContentType.CFACE);
					cmessage.setContent(m.getString(1));
				}
				//如果是个离线图片
				else if("offpic".equals(type)){
					cmessage.setContentType(MsgChat.ContentType.OFFPIC);
					JSONObject path=m.getJSONObject(1);
					cmessage.setContent(path.getString("file_path"));
					cmessage.setSuccess(path.getInt("success"));
				}
				
			}
			//如果是文字信息
			else{
				cmessage.setContentType(MsgChat.ContentType.TEXT);
				cmessage.setContent(msg);
			}
			
			chats.add(cmessage);
			
		}
		
		
		return chats;
	}
	
	
	
	
	
	

}
